<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px" style="width: 50%;">
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="formData.name"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入商品名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品分类" prop="categoryId">
      <el-cascader
        v-model="formData.categoryId"
        :options="categoryList"
        :props="defaultProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择商品分类"
      />
    </el-form-item>
    <el-form-item label="商品品牌" prop="brandId">
      <el-select v-model="formData.brandId" class="w-80" placeholder="请选择商品品牌">
        <el-option
          v-for="item in brandList"
          :key="item.id"
          :label="item.name"
          :value="item.id as number"
        />
      </el-select>
    </el-form-item>
    
    <el-form-item v-if="isBuiltInRole" label="适用门店" prop="status">
      <el-radio-group v-model="selectStore" class="w-80">
        <el-radio :label="0">全部门店</el-radio>
        <el-radio :label="1">部分门店</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="isBuiltInRole && selectStore === 1">
      <el-button @click="handleSelectStore" type="primary"> 选择门店</el-button>
      <el-table :data="storeTableRef" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="门店名称" align="center" prop="name" />
        <el-table-column label="联系方式"  prop="detailAddress" min-width="150">
          <template #default="scope">
            <div>联系电话：{{ scope.row.phone }}</div>
            <div>联系地址：{{ scope.row.detailAddress }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="180px" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['store:list:delete']">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    
    <el-form-item label="商品关键字" prop="keyword">
      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />
    </el-form-item>
    <el-form-item label="商品简介" prop="introduction">
      <el-input
        v-model="formData.introduction"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="128"
        placeholder="请输入商品简介"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品封面图" prop="picUrl">
      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
    </el-form-item>
    <el-form-item label="商品轮播图" prop="sliderPicUrls">
      <UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />
    </el-form-item>
  </el-form>

  <!-- 门店选择对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="选择门店"
    width="70%"
    destroy-on-close
  >
    <div class="store-dialog-scroll">
      <div class="store-grid">
        <div
          v-for="store in storeList"
          :key="store.id"
          class="store-card-simple"
          :class="{ 'is-selected': selectedStores.includes(store.id) }"
          @click="handleStoreSelect(store)"
        >
          <div class="store-name-simple">{{ store.name }}</div>
          <div class="store-status-simple" :class="{ 'open': isStoreOpen(store), 'closed': !isStoreOpen(store) }">
            {{ isStoreOpen(store) ? '营业中' : '休息中' }}
          </div>
          <div class="store-address-simple">{{ store.detailAddress }}</div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="confirmStoreSelection">保存</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { CategoryVO } from '@/api/mall/product/category'
import * as ProductBrandApi from '@/api/mall/product/brand'
import { BrandVO } from '@/api/mall/product/brand'
import { ListApi, ListVO } from '@/api/mall/store/list'
import { Location } from '@element-plus/icons-vue'
import { watch, nextTick } from 'vue'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗
const userStore = useUserStore() // 用户信息

const isBuiltInRole = computed(() => {
  const roles = userStore.getRoles
  return roles.some(role => role === 'super_admin' || role === 'tenant_admin')
})

const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  brandId: undefined, // 商品品牌
  status: 1 // 商品状态
})
const rules = reactive({
  name: [required],
  categoryId: [required],
  keyword: [required],
  introduction: [required],
  picUrl: [required],
  sliderPicUrls: [required],
  brandId: [required],
  status: [required]
})
const selectStore = ref(0)

const dialogVisible = ref(false)
const selectedStores = ref<number[]>([])

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  
  {
    immediate: true
  }
)

/** 选择门店按钮操作 */
const handleSelectStore = () => {
  dialogVisible.value = true
  // 初始化已选中的门店
  selectedStores.value = storeTableRef.value?.map(store => store.id) || []
}

/** 处理门店选择 */
const handleStoreSelect = (store: ListVO) => {
  const index = selectedStores.value.indexOf(store.id)
  if (index === -1) {
    selectedStores.value.push(store.id)
  } else {
    selectedStores.value.splice(index, 1)
  }
}

/** 确认门店选择 */
const confirmStoreSelection = () => {
  storeTableRef.value = storeList.value.filter(store => selectedStores.value.includes(store.id))
  dialogVisible.value = false
}

/** 删除门店 */
const handleDelete = (id: number) => {
  const index = storeTableRef.value?.findIndex(store => store.id === id)
  if (index !== undefined && index !== -1) {
    storeTableRef.value?.splice(index, 1)
    selectedStores.value = selectedStores.value.filter(storeId => storeId !== id)
  }
}

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate,
  getStoreInfo: () => ({
    selectStore: selectStore.value,
    storeList: storeList.value,
    storeTableRef: storeTableRef.value
  })
 })

/** 初始化 */
const brandList = ref<BrandVO[]>([]) // 商品品牌列表
const categoryList = ref<CategoryVO[]>([]) // 商品分类树
const storeList = ref<ListVO[]>([]) // 门店列表
const storeTableRef = ref<ListVO[]>([]) // 门店表格 Ref

// 监听 storeList 和 propFormData.storeIds，确保门店数据和回显数据都加载完再处理
watch(
  [() => storeList.value, () => props.propFormData.storeIds],
  async ([stores, storeIds]) => {
    if (!stores || stores.length === 0 || !storeIds) return
    let ids: number[] = []
    try {
      ids = typeof storeIds === 'string' ? JSON.parse(storeIds) : storeIds
    } catch {
      ids = []
    }
    const allStoreIds = stores.map(store => store.id).sort((a, b) => a - b)
    const selectedIds = [...ids].sort((a, b) => a - b)
    const isAll = allStoreIds.length === selectedIds.length && allStoreIds.every((id, idx) => id === selectedIds[idx])
    selectStore.value = isAll ? 0 : 1
    if (!isAll) {
      storeTableRef.value = stores.filter(store => selectedIds.includes(store.id))
    } else {
      storeTableRef.value = []
    }
  },
  { immediate: true }
)

onMounted(async () => {
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id')
  // 获取商品品牌列表
  brandList.value = await ProductBrandApi.getSimpleBrandList()
  storeList.value = await ListApi.getListList()
})

/** 判断门店是否营业中 */
function isStoreOpen(store: any) {
  if (!store.openingTime || !store.closingTime) return false;
  const now = new Date();
  const nowMinutes = now.getHours() * 60 + now.getMinutes();
  const [openH, openM] = store.openingTime.split(':').map(Number);
  const [closeH, closeM] = store.closingTime.split(':').map(Number);
  const openMinutes = openH * 60 + openM;
  const closeMinutes = closeH * 60 + closeM;
  if (openMinutes <= closeMinutes) {
    // 正常营业时间段
    return nowMinutes >= openMinutes && nowMinutes < closeMinutes;
  } else {
    // 跨天营业（如22:00-06:00）
    return nowMinutes >= openMinutes || nowMinutes < closeMinutes;
  }
}
</script>

<style scoped>
.store-dialog-scroll {
  height: 500px;
  overflow-y: auto;
  padding: 0 8px;
}
.store-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding: 20px 0;
}

.store-card-simple {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px 20px 12px 20px;
  background: #fff;
  cursor: pointer;
  transition: border-color 0.2s, box-shadow 0.2s;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.store-card-simple.is-selected {
  border: 2px solid var(--el-color-primary);
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.08);
}
.store-name-simple {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 4px;
  color: #222;
}
.store-status-simple {
  font-size: 14px;
  margin-bottom: 4px;
}
.store-status-simple.open {
  color: #13ce66;
  font-weight: 500;
}
.store-status-simple.closed {
  color: #f56c6c;
}
.store-address-simple {
  font-size: 13px;
  color: #888;
  word-break: break-all;
}
</style>
